﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

using NDatabase;
using NDatabase.Api;

namespace NDatabase.Repository
{
    /// <summary>
    /// NDatabase Context
    /// </summary>
    public class NDataBaseContext : INDatabaseContext, IDisposable
    {
        private readonly string _connectionStringName;
        private readonly IOdb _database;

        /// <summary>
        /// Gets the data base.
        /// </summary>
        /// <value>
        /// The data base <see cref="NDatabase.Api.IOdb" />.
        /// </value>
        public IOdb DataBase
        {
            get { return _database; }
        }

        /// <summary>
        /// Gets the name of the connection string.
        /// </summary>
        /// <value>
        /// The name of the connection string.
        /// </value>
        public string ConnectionStringName { get { return _connectionStringName; } }

        /// <summary>
        /// Initializes a new instance of the <see cref="NDataBaseContext"/> class.
        /// </summary>
        /// <param name="connectionStringName">Name of the connection string.</param>
        public NDataBaseContext(string connectionStringName)
        {
            _connectionStringName = connectionStringName;
            _database = GetOdb();

            NDatabaseContextHelper.Initialize(this);
        }

        /// <summary>
        /// Gets the odb.
        /// </summary>
        /// <returns></returns>
        private IOdb GetOdb()
        {
            var connectionString =
                System.Configuration.ConfigurationManager.ConnectionStrings[_connectionStringName].ConnectionString;
            return OdbFactory.Open(connectionString);
        }

        /// <summary>
        /// Saves the changes.
        /// </summary>
        public void SaveChanges()
        {
            _database.Commit();
        }

        /// <summary>
        /// 执行与释放或重置非托管资源相关的应用程序定义的任务。
        /// </summary>
        public void Dispose()
        {
            DataBase.Commit();
            DataBase.Dispose();
        }
    }
}
